package com.woniuxy.yoga.commons.alipay.util;


import cn.hutool.core.bean.BeanUtil;
import com.alipay.api.AlipayClient;
import com.alipay.api.internal.util.AlipaySignature;
import com.alipay.api.request.AlipayTradePagePayRequest;
import com.alipay.api.request.AlipayTradeQueryRequest;
import com.alipay.api.request.AlipayTradeRefundRequest;
import com.alipay.api.response.AlipayTradePagePayResponse;
import com.alipay.api.response.AlipayTradeQueryResponse;
import com.alipay.api.response.AlipayTradeRefundResponse;
import com.woniuxy.yoga.commons.alipay.config.ALiPayConfiguration;
import com.woniuxy.yoga.commons.alipay.data.AlipayParam;
import com.woniuxy.yoga.commons.alipay.data.PayStateResponseParam;
import com.woniuxy.yoga.commons.alipay.data.RefundParam;
import com.woniuxy.yoga.commons.alipay.data.RefundResponseParam;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

@Component
public class AlipayUtil {
    /**
     * 支付成功回调的交易状态名称
     */
    public static final String PAY_STATUS = "trade_status";//交易状态
    /**
     * 支付成功回调交易成功状态码
     */
    public static final String STATUS_SUCCESS = "TRADE_SUCCESS";//交易成功
    /**
     * 支付状态：交易创建，等待买家付款
     */
    public static final String STATUS_WAIT_PAY = "WAIT_BUYER_PAY";//交易待支付
    /**
     * 获取支付成功后回调的订单号
     */
    public static final String ORDER_NUM = "out_trade_no";//订单号
    /**
     * 获取支付成功后回调的支付时间
     */
    public static final String PAY_TIME = "gmt_payment";//支付时间
    /**
     * 统一内网穿透地址
     */
    public static final String NAT_APP_URL_LIU= "http://5ait62.natappfree.cc";//内网穿透地址

    /**
     * order内网穿透地址
     */
    public static final String NAT_APP_URL_LANG= "http://5ait62.natappfree.cc"; //内网穿透地址

    @Resource
    private AlipayClient alipayClient;

    @Resource
    private ALiPayConfiguration aLiPayConfiguration;

    /**
     * 网页支付方法 参数:封装支付参数，需要包含订单号、支付金额、支付说明、详细描述（可选）、同步回调地址、异步回调地址
     */
    public String payPage(AlipayParam param) throws Exception {
        // 实例化网页支付请求对象
        AlipayTradePagePayRequest request = new AlipayTradePagePayRequest();
        // 设置参数
        String content = "{\"out_trade_no\":\"" + param.getOutTradeNo() + "\"," + "\"total_amount\":\"" + param.getTotalAmount()
                + "\"," + "\"subject\":\"" + param.getSubject() + "\"," + "\"body\":\"" + param.getBody() + "\","
                + "\"product_code\":\"FAST_INSTANT_TRADE_PAY\""+","+"\"timeout_express\":\"" + "15m" +"\""+"}";
        request.setBizContent(content);
        //设置同步回调和异步回调
        request.setReturnUrl(param.getReturnUrl());
        request.setNotifyUrl(param.getNotifyUrl());
        //执行网页支付请求
        AlipayTradePagePayResponse response = alipayClient.pageExecute(request);
        //判断支付宝响应结果
        if(response.isSuccess()) {
            //返回支付宝响应的支付表单html内容
            return response.getBody();
        }
        throw new Exception("请求支付失败");
    }

    /**
     * 退款请求
     */
    public RefundResponseParam refund(RefundParam param) throws Exception{
        AlipayTradeRefundRequest request = new AlipayTradeRefundRequest();
        String out_request_no = UUID.randomUUID().toString();
        request.setBizContent("{\"out_trade_no\":\""+ param.getOut_trade_no() +"\","
                + "\"refund_amount\":\""+ param.getRefund_amount() +"\","
                + "\"refund_reason\":\""+ param.getRefund_reason() +"\","
                + "\"out_request_no\":\""+ out_request_no +"\"}");
        AlipayTradeRefundResponse response = alipayClient.execute(request);
        System.out.println("body = " + response.getBody());
        return BeanUtil.toBean(response, RefundResponseParam.class);
    }

    /**
     * 订单号查询支付状态
     */
    public PayStateResponseParam selPayState(String orderNum) throws Exception {
        AlipayTradeQueryRequest request = new AlipayTradeQueryRequest();
        request.setBizContent("{\"out_trade_no\":\""+orderNum+"\"}");
        AlipayTradeQueryResponse response = alipayClient.execute(request);
        System.out.println("body = " + response.getBody());
        return BeanUtil.toBean(response, PayStateResponseParam.class);
    }

    /**
     * 获得支付回调参数
     */
    public static Map<String,String> parseParams(Map<String, String[]> requestParams){
        //异步回调主要代码
        //获取支付宝POST过来的反馈信息
        //在控制层从request取出支付宝传过来的参数
        Map<String, String> params = new HashMap<>();
//        Map<String, String[]> requestParams = request.getParameterMap();
        for (String name : requestParams.keySet()) {
            String[] values = requestParams.get(name);
            String valueStr = "";
            for (int i = 0; i < values.length; i++) {
                valueStr = (i == values.length - 1) ? valueStr + values[i] : valueStr + values[i] + ",";
            }
            //乱码解决，这段代码在出现乱码时使用
//            valueStr = new String(valueStr.getBytes("ISO-8859-1"), "utf-8");
            params.put(name, valueStr);
        }
        return params;
    }

    /**
     * 验证参数是否合法
     */
    public boolean checkSignature(Map<String, String> params) throws Exception {
        return AlipaySignature.rsaCheckV1(params, aLiPayConfiguration.getAlipayPublicKey(), "utf-8", "RSA2");
    }
}
